<?php
if (!defined('SMF'))
	die('Hacking attempt...');

global $smcFunc, $txt, $scripturl, $settings, $user_info, $boarddir;
global $dbtables, $color_header, $color_line1, $color_line2;

// Verify user login, if CheckLogin() returns false return to the calling script/function
if (CheckLogin() == false)
	return;

require_once($boarddir . '/bnt/traderoute_funcs.php');

//-------------------------------------------------------------------------------------------------

// Pull player info.
$result = $smcFunc['db_query']('', '
	SELECT *
	FROM {raw:db_ships}
	WHERE user_id = {int:user_id}
	LIMIT 1',
	array(
		'db_ships' => $dbtables['ships'],
		'user_id' => $user_info['id'],
	)
);
$playerinfo = $smcFunc['db_fetch_assoc']($result);
$smcFunc['db_free_result']($result);

$result = $smcFunc['db_query']('', '
	SELECT *
	FROM {raw:db_traderoutes}
	WHERE owner = {int:ship_id}',
	array(
		'db_traderoutes' => $dbtables['traderoutes'],
		'ship_id' => $playerinfo['ship_id']
	)
);

$num_traderoutes = $smcFunc['db_num_rows']($result);

if ($num_traderoutes == 0)
	$traderoutes = '';
	
$i = 0;

while($row = $smcFunc['db_fetch_assoc']($result))
{
	$traderoutes[$i] = $row; 
	$i++;
}
$smcFunc['db_free_result']($result);

// Run check for illegal values and log any results
$freeholds = NUM_HOLDS($playerinfo['hull']) - $playerinfo['ship_ore'] - $playerinfo['ship_organics'] - $playerinfo['ship_goods'] - $playerinfo['ship_colonists'];
$maxholds = NUM_HOLDS($playerinfo['hull']);
$maxenergy = NUM_ENERGY($playerinfo['power']);

if ($playerinfo['ship_colonists'] < 0 || $playerinfo['ship_ore'] < 0 || $playerinfo['ship_organics'] < 0 || $playerinfo['ship_goods'] < 0 || $playerinfo['ship_energy'] < 0 || $freeholds < 0)
{
    if ($playerinfo['ship_colonists'] < 0 || $playerinfo['ship_colonists'] > $maxholds)
    {
        adminlog(LOG_ADMIN_ILLEGVALUE, $playerinfo['ship_id'], "$playerinfo[ship_name]|$playerinfo[ship_colonists]|colonists|$maxholds");
        $playerinfo['ship_colonists'] = 0;
    }
    if ($playerinfo['ship_ore'] < 0 || $playerinfo['ship_ore'] > $maxholds)
    {
        adminlog(LOG_ADMIN_ILLEGVALUE, $playerinfo['ship_id'], "$playerinfo[ship_name]|$playerinfo[ship_ore]|ore|$maxholds");
        $playerinfo['ship_ore'] = 0;
    }
    if ($playerinfo['ship_organics'] < 0 || $playerinfo['ship_organics'] > $maxholds)
    {
        adminlog(LOG_ADMIN_ILLEGVALUE, $playerinfo['ship_id'], "$playerinfo[ship_name]|$playerinfo[ship_organics]|organics|$maxholds");
        $playerinfo['ship_organics'] = 0;
    }
    if ($playerinfo['ship_goods'] < 0 || $playerinfo['ship_goods'] > $maxholds)
    {
        adminlog(LOG_ADMIN_ILLEGVALUE, $playerinfo['ship_id'], "$playerinfo[ship_name]|$playerinfo[ship_goods]|goods|$maxholds");
        $playerinfo['ship_goods'] = 0;
    }
    if ($playerinfo['hip_energy'] < 0 || $playerinfo['ship_energy'] > $maxenergy)
    {
        adminlog(LOG_ADMIN_ILLEGVALUE, $playerinfo['ship_id'], "$playerinfo[ship_name]|$playerinfo[ship_energy]|energy|$maxenergy");
        $playerinfo['ship_energy'] = 0;
    }
    if ($freeholds < 0)
        $freeholds = 0;
	
	// Reset illegal values to 0.
	$update = $smcFunc['db_query']('', '
		UPDATE {raw:db_ships}
		SET ship_ore = {int:ship_ore},
			ship_organics = {int:ship_organics},
			ship_goods = {int:ship_goods},
			ship_energy = {int:ship_energy},
			ship_colonists = {int:ship_colonists},
		WHERE ship_id = {int:ship_id}',
		array(
			'db_ships' => $dbtables['ships'],
			'ship_ore' => $playerinfo['ship_ore'],
			'ship_organics' => $playerinfo['ship_organics'],
			'ship_goods' => $playerinfo['ship_goods'],
			'ship_energy' => $playerinfo['ship_energy'],
			'ship_colonists' => $playerinfo['ship_colonists'],
			'ship_id' => $playerinfo['ship_id']
		)
	);
}

// Load REQUEST variables
if (isset($_GET['command']))
	$command = $_GET['command'];
else
	$command = '';
	
if (isset($_GET['traderoute_id']))
	$traderoute_id = (int) $_GET['traderoute_id'];

if (isset($_GET['confirm']))
	$confirm = $_GET['confirm'];
else
	$confirm = '';
	
// Take action based on the requested command
if ($command == 'new')				// Displays new trade route form
	traderoute_new('',$playerinfo,$num_traderoutes);
elseif ($command == 'create')		// Enters new route in db
	traderoute_create($playerinfo,$num_traderoutes);
elseif ($command == 'edit')			// Displays new trade route form, edit
	traderoute_new($traderoute_id,$playerinfo,$num_traderoutes);
elseif ($command == 'delete')		// Displays delete info
	traderoute_delete($traderoute_id,$confirm,$playerinfo);
elseif ($command == 'settings')		// Global traderoute settings form
	traderoute_settings($playerinfo);
elseif ($command == 'setsettings')	// Enters settings in db
	traderoute_setsettings($playerinfo);
elseif (isset($_GET['engage']))		// Performs trade route
	traderoute_engage($_GET['engage'],$playerinfo,$traderoutes);
else
	traderoute_display($playerinfo,$num_traderoutes,$traderoutes);	// Display all traderoutes


//-------------------------------------------------------------------------------------------------
//
//	Trade Route Actions
//
//-------------------------------------------------------------------------------------------------

function traderoute_engage($engage,$playerinfo,$traderoutes)
{
	global $smcFunc, $txt, $scripturl;
	global $dbtables;
	
	BigTitle($txt['bnt_tdr_title']);
	
	$arr_engage = explode(",",$engage);
	
	echo '
					<script type="text/javascript">
						$(document).ready(function(){
							// Table sorting function
							$("#tr_results").tablesorter({ 
								headers: {
									0: {sorter: false},
									1: {sorter: false},
									2: {sorter: false},
									3: {sorter: false},
									4: {sorter: false},
									5: {sorter: false},
									6: {sorter: false},
									7: {sorter: false},
									8: {sorter: false}
								},
								widgets: ["zebra","rowHover"]
							});
						});
					</script>
					<table id="tr_results" class="bnt_table">
						<thead>
							<tr>
								<th>Src</th>
								<th>Sector</th>
								<th>Trade Result</th>
								<th>Dest</th>
								<th>Sector</th>
								<th>Trade Result</th>
								<th>Turns</th>
								<th>Profit</th>
								<th>Status</th>
							</tr>
						</thead>
						<tbody>';
	
	for ($i = 0; $i < count($arr_engage); $i = $i + 2)
	{
		$result = $smcFunc['db_query']('', '
			SELECT *
			FROM {raw:db_traderoutes}
			WHERE owner = {int:ship_id}
			AND traderoute_id = {int:traderoute_id}',
			array(
				'db_traderoutes' => $dbtables['traderoutes'],
				'ship_id' => $playerinfo['ship_id'],
				'traderoute_id' => $arr_engage[$i]
			)
		);
		$cur_traderoute = $smcFunc['db_fetch_assoc']($result);
		$smcFunc['db_free_result']($result);
		
		echo '
							<tr id="traderoute_',  $arr_engage[$i], '">
								<td id="source_type_',  $arr_engage[$i], '">', $cur_traderoute['source_type'], '</td>
								<td id="source_sector_',  $arr_engage[$i], '">', $cur_traderoute['source_id'], '</td>
								<td id="source_result_',  $arr_engage[$i], '"></td>
								<td id="dest_type_',  $arr_engage[$i], '">', $cur_traderoute['dest_type'], '</td>
								<td id="dest_sector_',  $arr_engage[$i], '">', $cur_traderoute['dest_id'], '</td>
								<td id="dest_result_',  $arr_engage[$i], '"></td>
								<td id="single_run_turns_',  $arr_engage[$i], '"></td>
								<td id="single_run_profit_',  $arr_engage[$i], '"></td>
								<td id="status_',  $arr_engage[$i], '">pending</td>	
							</tr>';
	}
	
	echo '
						</tbody>
						<tfoot>
							<tr>
								<td colspan="6">Totals</td>
								<td id="total_turns"></td>
								<td id="total_profit"></td>
								<td></td>
							</tr>
						</tfoot>
					</table>';
	
	// Create template to hold trade runs results
	// Initiate javascript traderun function
	echo '
					<p id="tr_output">Traderoute Output</p>
					<p id="tr_status"></p>
					<script language="javascript" type="text/javascript">
						RunTradeRoute(', $engage, ');
					</script>';
	return;
}

function traderoute_display($playerinfo,$num_traderoutes,$traderoutes)
{
	global $smcFunc, $txt, $scripturl, $settings;
	global $dbtables;
	global $max_traderoutes_player;
	
	BigTitle($txt['bnt_tdr_title']);
	
	if ($num_traderoutes == 0)
		echo '<p>', $txt['bnt_tdr_noactive'], '</p>';
	else
	{
		echo '
				<script type="text/javascript">
					$(document).ready(function(){
						// Table sorting function
						$("#tr_table").tablesorter({ 
							headers: {
								0: {sorter: false},
								11: {sorter: false},
								12: {sorter: false}
							},
							widgets: ["zebra","rowHover"]
						});
					});
				</script>
				<input id="current_sector" type="hidden" value="', $playerinfo['sector'], '" />
				<div id="tr_runs">
					<div class="overlay"></div>
					<div id="tr_runs_content">
						<h4>Run Trade Routes</h4>
						<label for="traderoute_runs">Runs</label><input type="text" class="traderoute_runs" name="traderoute_runs" value="" size="2" maxlength="3" />
						<span id="engage" class="bnt_button ui-state-default ui-corner-all">', $txt['bnt_rs_engage_link'], '</span>
					</div>
				</div>
				<div id="tr_results"></div>
					<table id="tr_table" class="bnt_table">
						<thead>
							<tr>
								<th><input type="checkbox" class="check" id="tr_checkall" /></th>
								<th>', $txt['bnt_tdr_src'], '</th>
								<th>', $txt['bnt_sector'], '</th>
								<th>Type</th>
								<th>', $txt['bnt_tdr_dest'], '</th>
								<th>', $txt['bnt_sector'], '</th>
								<th>Type</th>
								<th>', $txt['bnt_tdr_move'], '</th>
								<th>', $txt['bnt_tdr_turns'], '</th>
								<th>', $txt['bnt_tdr_circuit'], '</th>
								<th>', $txt['bnt_energy'], '</th>
								<th></th>
								<th></th>
							</tr>
						</thead>
						<tbody>';
						
		$i = 0;
		
		while ($i < $num_traderoutes)
		{
			echo '
						<tr>
							<td>
								<input class="check" type="checkbox" name="traderoute_id" value="', $traderoutes[$i]['traderoute_id'], '"/>
							</td>
							<td>';
						
			if ($traderoutes[$i]['source_type'] == 'P')
				echo $txt['bnt_port'], '</td>
							<td class="rs_link">
								', $traderoutes[$i]['source_id'], '
							</td>';
			else
			{
				$result = $smcFunc['db_query']('', '
					SELECT name, sector_id
					FROM {raw:db_planets}
					WHERE planet_id = {int:source_id}',
					array(
						'db_planets' => $dbtables['planets'],
						'source_id' => $traderoutes[$i]['source_id']
					)
				);
				
				if ($smcFunc['db_num_rows']($result) > 0)
				{
					$planet1 = $smcFunc['db_fetch_assoc']($result);
					echo $planet1['name'], '</td>
							<td class="rs_link" href="#">
								', $planet1['sector_id'], '
							</td>';
				}
				else
					echo $txt['bnt_tdr_nonexistance'], '</td>';
					
				$smcFunc['db_free_result']($result);
			}

			echo '
							<td>';
			
			if ($traderoutes[$i]['source_type'] == 'P')
			{
				$result = $smcFunc['db_query']('', '
					SELECT *
					FROM {raw:db_universe}
					WHERE sector_id = {int:source_id}',
					array(
						'db_universe' => $dbtables['universe'],
						'source_id' => $traderoutes[$i]['source_id']
					)
				);
				$port1 = $smcFunc['db_fetch_assoc']($result);
				$smcFunc['db_free_result']($result);
				echo '&nbsp;', t_port_icon($port1['port_type']), '</td>';
			}
			else
			{
				if (empty($planet1))
					echo $txt['bnt_tdr_na'], '</td>';
				else
					echo $txt['bnt_tdr_cargo'], '</td>';
			}

			echo '
							<td>';

			if ($traderoutes[$i]['dest_type'] == 'P')
				echo $txt['bnt_port'], '</td>
							<td class="rs_link">
								', $traderoutes[$i]['dest_id'], '
							</td>';
			else
			{
				$result = $smcFunc['db_query']('', '
					SELECT name, sector_id
					FROM {raw:db_planets}
					WHERE planet_id = {int:dest_id}',
					array(
						'db_planets' => $dbtables['planets'],
						'dest_id' => $traderoutes[$i]['dest_id']
					)
				);
				if ($smcFunc['db_num_rows']($result) > 0)
				{
					$planet2 = $smcFunc['db_fetch_assoc']($result);
					echo $planet2['name'], '</td>
							<td class="rs_link" href="#">
								', $planet2['sector_id'], '
							</td>';
				}
				else
					echo $txt['bnt_tdr_nonexistance'], '</td>';
				$smcFunc['db_free_result']($result);
			}

			echo '
							<td>';
			
			if ($traderoutes[$i]['dest_type'] == 'P')
			{
				$result = $smcFunc['db_query']('', '
					SELECT *
					FROM {raw:db_universe}
					WHERE sector_id = {int:dest_id}',
					array(
						'db_universe' => $dbtables['universe'],
						'dest_id' => $traderoutes[$i]['dest_id']
					)
				);
				$port2 = $smcFunc['db_fetch_assoc']($result);
				$smcFunc['db_free_result']($result);
				echo t_port_icon($port2['port_type']), '</td>';
			}
			else
			{
				if (empty($planet2))
					echo $txt['bnt_tdr_na'], '</td>';
				else
				{
					if ($playerinfo['trade_colonists'] == 'N' && $playerinfo['trade_fighters'] == 'N' && $playerinfo['trade_torps'] == 'N')
						echo $txt['bnt_tdr_none'];
					else
					{
						if ($playerinfo['trade_colonists'] == 'Y')
							echo t_port_icon($txt['bnt_tdr_colonists']);
						if ($playerinfo['trade_fighters'] == 'Y')
							echo t_port_icon($txt['bnt_tdr_fighters']);
						if ($playerinfo['trade_torps'] == 'Y')
							echo t_port_icon($txt['bnt_tdr_torps']);
					}
					echo '</td>';
				}
			}
			
			if ($traderoutes[$i]['move_type'] == 'R')
			{
				echo '		
							<td>RS</td>
							<td>';

				if ($traderoutes[$i]['source_type'] == 'P')
					$src = $port1;
				else
					$src = $planet1['sector_id'];

				if($traderoutes[$i]['dest_type'] == 'P')
					$dst = $port2;
				else
					$dst = $planet2['sector_id'];

				$dist = traderoute_distance($traderoutes[$i]['source_type'], $traderoutes[$i]['dest_type'], $src, $dst, $traderoutes[$i]['circuit']);
				echo $dist['triptime'], '</td>
							<td>';
				
				if ($traderoutes[$i]['circuit'] == '1')
					echo '1 ', $txt['bnt_tdr_way'], '</td>';
				else
					echo '2 ', $txt['bnt_tdr_way'], '</td>';
				
				if ($traderoutes[$i]['circuit'] == '1')
					$energy_scooped = NUMBER($dist['scooped'] * 2);
				else
					$energy_scooped = NUMBER($dist['scooped']);
					
				echo '
							<td>', str_replace("[tdr_dist_scooped]", $energy_scooped, $txt['bnt_tdr_escooped2']), '</td>';
			}
			else
			{
				echo '
							<td>', $txt['bnt_tdr_warp'], '</td>
							<td>';
				
				if ($traderoutes[$i]['circuit'] == '1')
					echo '2';
				else
					echo '4';
					
				echo '</td>
							<td>';
					
				if ($traderoutes[$i]['circuit'] == '1')
					echo '1 ', $txt['bnt_tdr_way'];
				else
					echo '2 ', $txt['bnt_tdr_way'];	
				
				echo '</td>
							<td>0</td>';
			}
			
			echo '
							</td>
							<td id="tr_edit">
								<span class="bnt_icon ui-icon ui-icon-wrench"></span><input type="hidden" value="', $traderoutes[$i]['traderoute_id'], '" />
							</td>
							<td id="tr_delete">
								<span class="bnt_icon ui-icon ui-icon-trash"></span><input type="hidden" value="', $traderoutes[$i]['traderoute_id'], '" />
							</td>
						</tr>';

			$i++;
		}

		echo '
						</tbody>
					</table>
				<div id="tr_dialog" class="dialog" title="Delete Trade Route"></div>';
	}
}

function traderoute_new($traderoute_id,$playerinfo,$num_traderoutes)
{
	global $smcFunc, $txt, $scripturl;
	global $dbtables;
	global $max_traderoutes_player;
	
	BigTitle($txt['bnt_tdr_title']);
	
	if (!empty($traderoute_id))
	{
		$result = $smcFunc['db_query']('', '
			SELECT *
			FROM {raw:db_traderoutes}
			WHERE traderoute_id = {int:traderoute_id}',
			array(
				'db_traderoutes' => $dbtables['traderoutes'],
				'traderoute_id' => $traderoute_id
			)
		);
		
		if($smcFunc['db_num_rows']($result) == 0)
		{
			echo '<p>', $txt['bnt_tdr_editerr'], '</p>';
			return;
		}
			
		$editroute = $smcFunc['db_fetch_assoc']($result);
		
		if($editroute['owner'] != $playerinfo['ship_id'])
		{
			echo '<p>', $txt['bnt_tdr_notowner'], '</p>';
			return;
		}
			
		$smcFunc['db_free_result']($result);
	}

	if ($num_traderoutes >= $max_traderoutes_player && empty($editroute))
	{
		echo '<p>', $txt['bnt_tdr_maxtdr'], '</p>';
		return;
	}

	echo '<p><font size=3 color=blue><b>';
	
	if (empty($editroute))
		echo $txt['bnt_tdr_createnew'];
	else
		echo $txt['bnt_tdr_editinga'], ' ';
		
	echo $txt['bnt_tdr_traderoute'], '</b></font></p>';
	
	// Get Planet info Corp and Personal (BEGIN)
	$result = $smcFunc['db_query']('', '
		SELECT *
		FROM {raw:db_planets}
		WHERE owner = {int:ship_id}
		ORDER BY sector_id',
		array(
			'db_planets' => $dbtables['planets'],
			'ship_id' => $playerinfo['ship_id']
		)
	);

	$num_planets = $smcFunc['db_num_rows']($result);
	$i = 0;
	
	while ($planets[$i] = $smcFunc['db_fetch_assoc']($result))
	{
		if ($planets[$i]['name'] == "")
			$planets[$i]['name'] = $txt['bnt_tdr_unnamed'];
		$i++;
	}
	$smcFunc['db_free_result']($result);
	
	$result = $smcFunc['db_query']('', '
		SELECT *
		FROM {raw:db_planets}
		WHERE corp = {int:team}
		AND  corp != 0
		AND owner <> {int:ship_id}
		ORDER BY sector_id',
		array(
			'db_planets' => $dbtables['planets'],
			'team' => $playerinfo['team'],
			'ship_id' => $playerinfo['ship_id']
		)
	);

	$num_corp_planets = $smcFunc['db_num_rows']($result);
	$i = 0;
  
	while ($planets_corp[$i] = $smcFunc['db_fetch_assoc']($result))
	{
		if($planets_corp[$i]['name'] == "")
			$planets_corp[$i]['name'] = $txt['bnt_tdr_unnamed'];
		$i++;
	}
	// Get Planet info Corp and Personal (END)

	// Display Current Sector
	echo $txt['bnt_tdr_cursector'], ' ', $playerinfo['sector'], '<br><br>';
	
	// Error frame
	echo '
				<div id="tr_error_frame">
					<div class="overlay"></div>
					<div id="content">
						<h4 class="tr_error_title">', $txt['bnt_error'], '</h4>
						<div id="tr_error_message"></div>
					</div>
				</div>';
	
	// Start of form for starting location
	echo '
		<form action="">
		<table border="0">
			<tr>
				<td align="right"><font size=2><b>', $txt['bnt_tdr_selspoint'], '<br>&nbsp;</b></font></td>
					<tr>
						<td align="right"><font size=2>', $txt['bnt_tdr_port'],' : </font></td>
							<td><input type="radio" name="ptype1" value="port"';

	if (empty($editroute) || (!empty($editroute) && $editroute['source_type'] == 'P'))
		echo " checked";

	echo '></td>
							<td>&nbsp;&nbsp;<input type="text" name="port_id1" size="20" align="center"';

	if (!empty($editroute) && $editroute['source_type'] == 'P')
		echo ' value="', $editroute['source_id'], '"';

	echo '></td>
						</tr>';

	//-------------------- Personal Planet
	echo '
						<tr>
							<td align="right"><font size=2>', $txt['bnt_planet_mcorp_linkP'], ' : </font></td>
							<td><input type="radio" style="check" name="ptype1" value="planet"';
							
	if (!empty($editroute) && $editroute['source_type'] == 'L')
		echo ' checked';

    echo '></td>
						    <td>&nbsp;&nbsp;<select name="planet_id1">';

	if ($num_planets == 0)
		echo '
								<option value="none">', $txt['bnt_tdr_none'], '</option>';
	else
	{
		$i = 0;
		while ($i < $num_planets)
		{
			echo '
								<option ';
			if (!empty($editroute) && $planets[$i]['planet_id'] == $editroute['source_id'])
				echo 'selected ';
			echo 'value="', $planets[$i]['planet_id'], '">', $planets[$i]['name'], ' ', $txt['bnt_tdr_insector'], ' ', $planets[$i]['sector_id'], '</option>';
			$i++;
		}
	}
	
	echo '
							</td>
						</tr>';
	
	//----------------------- Corp Planet
    echo '
						<tr>
							<td align="right"><font size="2">', $txt['bnt_planet_mcorp_linkC'], ' : </font></td>
							<td><input type="radio" style="check"  name="ptype1" value="corp_planet"';

	if (!empty($editroute) && $editroute['source_type'] == 'C')
		echo " checked";

	echo '></td>
							<td>&nbsp;&nbsp;<select name="corp_planet_id1">';

	if ($num_corp_planets == 0)
		echo '									<option value=none>', $txt['bnt_tdr_none'], '</option>';
	else
	{
		$i = 0;
		while ($i < $num_corp_planets)
		{
			echo '								<option ';
			if( $planets_corp[$i]['planet_id'] == $editroute['source_id'])
				echo 'selected ';
			echo 'value=', $planets_corp[$i]['planet_id'], '>', $planets_corp[$i]['name'], ' ', $txt['bnt_tdr_insector'], ' ', $planets_corp[$i]['sector_id'], '</option>';
			$i++;
		}
	}
	echo '
							</select>
						</tr>';
						
	//----------------------- End Start point selection
	
	//----------------------- Begin Ending point selection
	echo '
						<tr>
							<td>&nbsp;</td>
						</tr>
						<tr>
							<td align="right"><font size=2><b>', $txt['bnt_tdr_selendpoint'], ' : <br>&nbsp;</b></font></td>
						<tr>
							<td align="right"><font size=2>', $txt['bnt_tdr_port'], ' : </font></td>
							<td><input type="radio" style="check" name="ptype2" value="port"';

	if (empty($editroute) || (!empty($editroute) && $editroute['dest_type'] == 'P'))
		echo " checked";

	echo '></td>
							<td>&nbsp;&nbsp;<input type=text name=port_id2 size=20 align="center"';

	if (!empty($editroute) && $editroute['dest_type'] == 'P')
		echo ' value="', $editroute['dest_id'], '"';

    echo '></td>
						</tr>';
						
	//-------------------- Personal Planet
	echo '				<tr>
							<td align="right"><font size=2>', $txt['bnt_planet_mcorp_linkP'], ' : </font></td>
							<td><input type="radio" style="check" name="ptype2" value="planet"';

	if(!empty($editroute) && $editroute['dest_type'] == 'L')
		echo ' checked';

	echo '></td>
							<td>&nbsp;&nbsp;<select name="planet_id2">';

	if ($num_planets == 0)
		echo '
												<option value="none">', $txt['bnt_tdr_none'], '</option>';
	else
	{
		$i = 0;
		while ($i < $num_planets)
		{
			echo '
												<option ';
			if (!empty($editroute) && $planets[$i]['planet_id'] == $editroute['dest_id'])
				echo 'selected ';
			echo 'value=', $planets[$i]['planet_id'], '>', $planets[$i]['name'], ' ', $txt['bnt_tdr_insector'], ' ', $planets[$i]['sector_id'], '</option>';
			$i++;
		}
	}
	
	echo '
							</td>
						</tr>';
						
	//----------------------- Corp Planet
	echo '
						<tr>
							<td align="right"><font size=2>', $txt['bnt_planet_mcorp_linkC'], ' : </font></td>
							<td><input type="radio" style="check" name="ptype2" value="corp_planet"';

	if (!empty($editroute) && $editroute['dest_type'] == 'C')
		echo " checked";

    echo ' ></td>
							<td>&nbsp;&nbsp;<select name="corp_planet_id2">';

	if ($num_corp_planets == 0)
		echo '<option value="none">', $txt['bnt_tdr_none'], '</option>';
	else
	{
		$i = 0;
		while ($i < $num_corp_planets)
		{
			echo '<option ';
			if ($planets_corp[$i]['planet_id'] == $editroute['dest_id'])
				echo 'selected ';
			echo 'value=', $planets_corp[$i]['planet_id'], '>', $planets_corp[$i]['name'], ' ', $txt['bnt_tdr_insector'], ' ', $planets_corp[$i]['sector_id'], '</option>';
			$i++;
		}
	}
	echo '					</select>
						</tr>';
	//----------------------- End finishing point selection

	echo '				</select>
					</tr>
					<tr>
						<td>&nbsp;</td>
					</tr>
					<tr>
						<td align="right"><font size=2><b>', $txt['bnt_tdr_selmovetype'], ' : </b></font></td>
						<td colspan=2 valign=top><font size=2><input type="radio" name="move_type" value="realspace"';

	if (empty($editroute) || (!empty($editroute) && $editroute['move_type'] == 'R'))
		echo ' checked';

	echo '>&nbsp;', $txt['bnt_tdr_realspace'], '&nbsp;&nbsp<font size=2><input type="radio" style="check" name="move_type" value="warp"';

	if (!empty($editroute) && $editroute['move_type'] == 'W')
		echo ' checked';

	echo '>&nbsp;', $txt['bnt_tdr_warp'], '</font></td>
					</tr>
					<tr>
						<td align="right"><font size=2><b>', $txt['bnt_tdr_selcircuit'], ' : </b></font></td>
						<td colspan=2 valign=top><font size=2><input type="radio" style="check" name="circuit_type" value="1"';

	if (empty($editroute) || (!empty($editroute) && $editroute['circuit'] == '1'))
		echo ' checked';

	echo '>&nbsp;', $txt['bnt_tdr_oneway'], '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="radio" style="check" name="circuit_type" value="2"';

	if (!empty($editroute) && $editroute['circuit'] == '2')
		echo " checked";

	echo '>&nbsp;', $txt['bnt_tdr_bothways'], '</font></td>
					</tr>
					<tr>
						<td>&nbsp;</td>
					</tr>
					<tr>
						<td><td>
						<td align="center">';

	if (empty($editroute))
		echo '				
							<a id="tr_create" class="bnt_button ui-state-default ui-corner-all" href="#">', $txt['bnt_tdr_create'], '</a>';
	else
	{
		echo '				<input type="hidden" name="editing" value=', $editroute['traderoute_id'], '>
							<a id="tr_create" class="bnt_button ui-state-default ui-corner-all" href="#">', $txt['bnt_tdr_modify'], '</a>';
	}

	echo '				</td>
					</tr>
				</table>
				</form>';
}

function traderoute_create($playerinfo,$num_traderoutes)
{
	global $smcFunc, $txt, $scripturl;
	global $dbtables;
	global $max_traderoutes_player;
	
	// Get the request variables from the new traderoute form
	$ptype1 = (isset($_GET['ptype1'])) ? $_GET['ptype1'] : '';
	$ptype2 = (isset($_GET['ptype2'])) ? $_GET['ptype2'] : '';
	$port_id1 = (isset($_GET['port_id1'])) ? (int) $_GET['port_id1'] : '';
	$port_id2 = (isset($_GET['port_id2'])) ? (int) $_GET['port_id2'] : '';
	$planet_id1 = (isset($_GET['planet_id1'])) ? (int) $_GET['planet_id1'] : '';
	$planet_id2 = (isset($_GET['planet_id2'])) ? (int) $_GET['planet_id2'] : '';
	$corp_planet_id1 = (isset($_GET['corp_planet_id1'])) ? (int) $_GET['corp_planet_id1'] : '';
	$corp_planet_id2 = (isset($_GET['corp_planet_id2'])) ? (int) $_GET['corp_planet_id2'] : '';
	$move_type = (isset($_GET['move_type'])) ? $_GET['move_type'] : '';
	$circuit_type = (isset($_GET['circuit_type'])) ? $_GET['circuit_type'] : '';
	$editing = (isset($_GET['editing'])) ? $_GET['editing'] : '';
	
	// Make sure we are getting what we expect from the source and dest request variables
	if ($ptype1 != 'port' && $ptype1 != 'planet' && $ptype1 != 'corp_planet')
	{
		echo '<input type="hidden" id="status" value="', $txt['bnt_tdr_badsource'], '" />';
		die();
	}
	if ($ptype2 != 'port' && $ptype2 != 'planet' && $ptype2 != 'corp_planet')
	{
		echo '<input type="hidden" id="status" value="', $txt['bnt_tdr_baddest'], '" />';
		die();
	}
		
	// Do not let the player exceed the max traderoutes.
    if ($num_traderoutes >= $max_traderoutes_player && empty($editing))
	{
		echo '<input type="hidden" id="status" value="', $txt['bnt_tdr_maxtdr'], '" />';
		die();
	}
	
	// Database sanity check for source.
	if ($ptype1 == 'port')
	{
		$result = $smcFunc['db_query']('', '
			SELECT *
			FROM {raw:db_universe}
			WHERE sector_id = {int:port_id1}',
			array(
				'db_universe' => $dbtables['universe'],
				'port_id1' => $port_id1
			)
		);
		
		if ($smcFunc['db_num_rows']($result) == 0)
		{
			$txt['bnt_tdr_errnotvalidport'] = str_replace("[tdr_port_id]", $port_id1, $txt['bnt_tdr_errnotvalidport']);
			echo '<input type="hidden" id="status" value="', $txt['bnt_tdr_errnotvalidport'], '" />';
			die();
		}
		
		//If we made it this far, then we have a port.
		$source = $smcFunc['db_fetch_assoc']($result);
		$smcFunc['db_free_result']($result);
		
		if ($source['port_type'] == 'none')
		{
			$txt['bnt_tdr_errnoport'] = str_replace("[tdr_port_id]", $port_id1, $txt['bnt_tdr_errnoport']);
			echo '<input type="hidden" id="status" value="', $txt['bnt_tdr_errnoport'], '" />';
			die();
		}
	}
	else
	{
		$result = $smcFunc['db_query']('', '
			SELECT *
			FROM {raw:db_planets}
			WHERE planet_id = {int:planet_id1}',
			array(
				'db_planets' => $dbtables['planets'],
				'planet_id1' => $planet_id1
			)
		);
		$source = $smcFunc['db_fetch_assoc']($result);
		
		if ($smcFunc['db_num_rows']($result) == 0)
		{
			echo '<input type="hidden" id="status" value="', $txt['bnt_tdr_errnosrc'], '" />';
			die();
		}
		
		$smcFunc['db_free_result']($result);

		if ($source['owner'] != $playerinfo['ship_id'])
		{
			if (($playerinfo['team'] == 0 || $playerinfo['team'] != $source['corp']) && $source['sells'] == 'N')
			{
				$txt['bnt_tdr_errnotownnotsell'] = str_replace("[tdr_source_name]", $source['name'], $txt['bnt_tdr_errnotownnotsell']);
				$txt['bnt_tdr_errnotownnotsell'] = str_replace("[tdr_source_sector_id]", $source['sector_id'], $txt['bnt_tdr_errnotownnotsell']);
				echo '<input type="hidden" id="status" value="', $txt['bnt_tdr_errnotownnotsell'], '" />';
				die();
			}
		}
	}
	
	//OK we have $source, *probably* now lets see if we have ever been there.
	//Attempting to fix the map the universe via traderoute bug. -- rjordan01

	$result = $smcFunc['db_query']('', '
		SELECT *
		FROM {raw:db_movement_log}
		WHERE sector_id = {int:sector_id}
		AND ship_id = {int:ship_id}',
		array(
			'db_movement_log' => $dbtables['movement_log'],
			'sector_id' => $source['sector_id'],
			'ship_id' => $playerinfo['ship_id']
		)
	);
	
	if ($smcFunc['db_num_rows']($result) == 0)
	{
		echo '<input type="hidden" id="status" value="', $txt['bnt_tdr_unksector'], '" />';
		die();
	}
		
	$smcFunc['db_free_result']($result);

	// Database sanity check for dest.
	if ($ptype2 == 'port')
	{
		$result = $smcFunc['db_query']('', '
			SELECT *
			FROM {raw:db_universe}
			WHERE sector_id = {int:port_id2}',
			array(
				'db_universe' => $dbtables['universe'],
				'port_id2' => $port_id2
			)
		);
		
		if ($smcFunc['db_num_rows']($result) == 0)
		{
			$txt['bnt_tdr_errnotvaliddestport'] = str_replace("[tdr_port_id]", $port_id2, $txt['bnt_tdr_errnotvaliddestport']);
			echo '<input type="hidden" id="status" value="', $txt['bnt_tdr_errnotvaliddestport'], '" />';
			die();
		}
		
		$destination = $smcFunc['db_fetch_assoc']($result);
		$smcFunc['db_free_result']($result);
		
		if ($destination['port_type'] == 'none')
		{
			$txt['bnt_tdr_errnoport2'] = str_replace("[tdr_port_id]", $port_id2, $txt['bnt_tdr_errnoport2']);
			echo '<input type="hidden" id="status" value="', $txt['bnt_tdr_errnoport2'], '" />';
			die();
		}
	}
	else
	{
		$result = $smcFunc['db_query']('', '
			SELECT *
			FROM {raw:db_planets}
			WHERE planet_id = {int:planet_id2}',
			array(
				'db_planets' => $dbtables['planets'],
				'planet_id2' => $planet_id2
			)
		);
		
		if ($smcFunc['db_num_rows']($result) == 0)
		{
			echo '<input type="hidden" id="status" value="', $txt['bnt_tdr_errnodestplanet'], '" />';
			die();
		}
		
		$destination = $smcFunc['db_fetch_assoc']($result);
		$smcFunc['db_free_result']($result);
		
		if ($destination['owner'] != $playerinfo['ship_id'] && $destination['sells'] == 'N')
		{
			$txt['bnt_tdr_errnotownnotsell2'] = str_replace("[tdr_dest_name]", $destination['name'], $txt['bnt_tdr_errnotownnotsell2']);
			$txt['bnt_tdr_errnotownnotsell2'] = str_replace("[tdr_dest_sector_id]", $destination['sector_id'], $txt['bnt_tdr_errnotownnotsell2']);
			echo '<input type="hidden" id="status" value="', $txt['bnt_tdr_errnotownnotsell2'], '" />';
			die();
		}
	}
	
	// OK now we have $destination lets see if we've been there.
	$result = $smcFunc['db_query']('', '
		SELECT *
		FROM {raw:db_movement_log}
		WHERE sector_id = {int:sector_id}
		AND ship_id = {int:ship_id}',
		array(
			'db_movement_log' => $dbtables['movement_log'],
			'sector_id' => $destination['sector_id'],
			'ship_id' => $playerinfo['ship_id']
		)
	);
	
	if ($smcFunc['db_num_rows']($result) == 0)
	{
		echo '<input type="hidden" id="status" value="', $txt['bnt_tdr_unksector'], '" />';
		die();
	}
	
	//check destination - we cannot trade INTO a special port
	if (array_key_exists('port_type', $destination) && $destination['port_type'] == 'special')
	{
		echo '<input type="hidden" id="status" value="', $txt['bnt_tdr_nospecial'], '" />';
		die();
	}

	//check traderoute for src => dest
	traderoute_check_compatible($ptype1, $ptype2, $move_type, $circuit_type, $source , $destination);

	if ($ptype1 == 'port')
		$src_id = $port_id1;
	elseif($ptype1 == 'planet')
		$src_id = $planet_id1;
	elseif($ptype1 == 'corp_planet')
		$src_id = $corp_planet_id1;

	if ($ptype2 == 'port')
		$dest_id = $port_id2;
	elseif($ptype2 == 'planet')
		$dest_id = $planet_id2;
	elseif($ptype2 == 'corp_planet')
		$dest_id = $corp_planet_id2;

	if ($ptype1 == 'port')
		$src_type = 'P';
	elseif($ptype1 == 'planet')
		$src_type = 'L';
	elseif($ptype1 == 'corp_planet')
		$src_type = 'C';

	if ($ptype2 == 'port')
		$dest_type = 'P';
	elseif($ptype2 == 'planet')
		$dest_type = 'L';
	elseif($ptype2 == 'corp_planet')
		$dest_type = 'C';

	if ($move_type == 'realspace')
		$mtype = 'R';
	else
		$mtype = 'W';

	if (empty($editing))
	{
		$smcFunc['db_insert']('insert',
			$dbtables['traderoutes'],
			array(
				'source_id' => 'int',
				'dest_id' => 'int',
				'source_type' => 'string',
				'dest_type' => 'string',
				'move_type' => 'string',
				'owner' => 'int',
				'circuit' => 'string'
			),
			array(
				$src_id,
				$dest_id,
				$src_type,
				$dest_type,
				$mtype,
				$playerinfo['ship_id'],
				$circuit_type
			),
			''
		);
		echo '		<input type="hidden" id="status" value="complete" />
					<p>', $txt['bnt_tdr_newtdrcreated'], '</p>';
	}
	else
	{
		$update = $smcFunc['db_query']('', '
			UPDATE {raw:db_traderoutes}
			SET source_id = {int:src_id},
				dest_id = {int:dest_id},
				source_type = {string:src_type},
				dest_type = {string:dest_type},
				move_type = {string:mtype},
				owner = {int:ship_id},
				circuit = {string:circuit_type}
			WHERE traderoute_id = {int:editing}',
			array(
				'db_traderoutes' => $dbtables['traderoutes'],
				'ship_id' => $playerinfo['ship_id'],
				'src_id' => $src_id,
				'dest_id' => $dest_id,
				'src_type' => $src_type,
				'dest_type' => $dest_type,
				'mtype' => $mtype,
				'circuit_type' => $circuit_type,
				'editing' => $editing
			)
		);
		echo '		<input type="hidden" id="status" value="complete" />
					<p>', $txt['bnt_tdr_tdrmodified'], '</p>';
	}
}

function traderoute_delete($traderoute_id,$confirm,$playerinfo)
{	
	global $smcFunc, $txt, $scripturl;
	global $dbtables, $color_line1, $color_line2, $color_header;
	
	// Get the traderoute that may be deleted.
	$result = $smcFunc['db_query']('', '
		SELECT *
		FROM {raw:db_traderoutes}
		WHERE traderoute_id = {int:traderoute_id}
		AND owner = {int:owner}
		LIMIT 1',
		array(
			'db_traderoutes' => $dbtables['traderoutes'],
			'traderoute_id' => $traderoute_id,
			'owner' => $playerinfo['ship_id']
		)
	);
	
	if ($smcFunc['db_num_rows']($result) == 0)
		traderoute_die($txt['bnt_tdr_doesntexist']);

	$delroute = $smcFunc['db_fetch_assoc']($result);
	$smcFunc['db_free_result']($result);

	if ($delroute['owner'] != $playerinfo['ship_id'])
		traderoute_die($txt['bnt_tdr_notowntdr']);
	
	// Here it continues to the main file area to print the route
	if (empty($confirm))
	{
		echo '
					<p>Source: ', $delroute['source_type'], ' in sector ', $delroute['source_id'], '</p>
					<p>Destination: ', $delroute['dest_type'], ' in sector ', $delroute['dest_id'], '</p>';
	}
	else
	{
		$result = $smcFunc['db_query']('', '
			DELETE FROM {raw:db_traderoutes}
			WHERE traderoute_id = {int:traderoute_id}',
			array(
				'db_traderoutes' => $dbtables['traderoutes'],
				'traderoute_id' => $traderoute_id
			)
		);
		echo "$txt[bnt_tdr_tdrdeleted] $txt[bnt_tdr_returnmenu]";
		traderoute_die("");
		return;
	}
}

function traderoute_settings($playerinfo)
{
	global $smcFunc, $txt, $scripturl;
	global $dbtables, $color_line1, $color_line2, $color_header;
	
	BigTitle($txt['bnt_tdr_title']);
	
	echo '<p><font size=3 color=blue><b>', $txt['bnt_tdr_globalset'], '</b></font></p>';

	echo '	<font color=white size=2><b>', $txt['bnt_tdr_tdrsportsrc'], ' :</b></font><p>
		    <table border=0>
					<tr>
					    <td><font size="2" color="white"> - ', $txt['bnt_tdr_colonists'], ' :</font></td>
					    <td><input type="checkbox" style="check" name="colonists" id="trade_colonists"';

	if ($playerinfo['trade_colonists'] == 'Y')
		echo ' checked';

	echo '>			
					</tr>
					<tr>
						<td><font size="2" color="white"> - ', $txt['bnt_tdr_fighters'], ' :</font></td>
						<td><input type="checkbox" style="check" name="fighters" id="trade_fighters"';

	if ($playerinfo['trade_fighters'] == 'Y')
		echo ' checked';

	echo '>
					</tr>
					<tr>
					    <td><font size="2" color="white"> - ', $txt['bnt_tdr_torps'], ' :</font></td>
					    <td><input type=checkbox style="check" name="torps" id="trade_torps"';

	if ($playerinfo['trade_torps'] == 'Y')
		echo ' checked';

	echo '>
				</tr>
				</table>
				<p><td><font size="2" color="white"><b>', $txt['bnt_tdr_tdrescooped'], ' :</b></font></p>
			    <table border=0>
					<tr>
						<td><td><font size="2" color="white">&nbsp;&nbsp;&nbsp;', $txt['bnt_tdr_trade'], '</font></td>
						<td><input type="radio" style="check" name="trade_energy" value="Y"';

	if ($playerinfo['trade_energy'] == 'Y')
		echo ' checked';

	echo '></td>
					</tr>
					<tr>
						<td><td><font size="2" color="white">&nbsp;&nbsp;&nbsp;', $txt['bnt_tdr_keep'], '</font></td>
					    <td><input type="radio" style="check" name="trade_energy" value="N"';

	if ($playerinfo['trade_energy'] == 'N')
		echo ' checked';

	echo '></td>
					</tr>
					<tr>
						<td></td>
					</tr>
					<tr>
						<td><input type="hidden" name="shipid" id="trade_shipid" value=', $playerinfo['ship_id'], '></td>
						<td><a id="tr_setsettings" class="bnt_button ui-state-default ui-corner-all" href="#">', $txt['bnt_tdr_save'], '</a></td>
					</tr>
				</table>
				</form>';
}

function traderoute_setsettings($playerinfo)
{
	global $smcFunc, $txt;
	global $dbtables, $color_line1, $color_line2, $color_header;

	BigTitle($txt['bnt_tdr_title']);
	
	$colonists = (isset($_GET['trade_colonists'])) ? $_GET['trade_colonists'] : 'N';
	$fighters =(isset($_GET['trade_fighters'])) ? $_GET['trade_fighters'] : 'N';
	$torps = (isset($_GET['trade_torps'])) ? $_GET['trade_torps'] : 'N';
	$energy = (isset($_GET['trade_energy'])) ? $_GET['trade_energy'] : 'N';
	$ship_id = $_GET['trade_shipid'];
	
	$update = $smcFunc['db_query']('', '
		UPDATE {raw:db_ships}
		SET trade_colonists = {string:colonists},
			trade_fighters = {string:fighters},
			trade_torps = {string:torps},
			trade_energy = {string:energy}
		WHERE ship_id = {int:ship_id}',
		array(
			'db_ships' => $dbtables['ships'],
			'colonists' => $colonists,
			'fighters' => $fighters,
			'torps' => $torps,
			'energy' => $energy,
			'ship_id' => $ship_id,
		)
	);

	echo $txt['bnt_tdr_globalsetsaved'];
}

?>
